package com.all.play.myapplication.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;

import com.all.play.myapplication.R;
import com.all.play.myapplication.adapter.ImagePickerAdapter;
import com.all.play.myapplication.base.BaseFragment;
import com.all.play.myapplication.utils.Constants;
import com.all.play.myapplication.utils.HttpUtil;
import com.all.play.myapplication.utils.MyStringCallBack;
import com.all.play.myapplication.utils.SharedPreferencesUtil;
import com.all.play.myapplication.view.SelectDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * Created by 聪明一只哈 on 2018/4/18.
 * Time: 2018/4/18  15:02
 */

public class MoreFragment extends BaseFragment implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private int maxImgCount = 22;


    @BindView(R.id.recyclerView_imagepick)
    RecyclerView recyclerView_imagepick;
    @BindView(R.id.scro_webview)
    WebView scro_webview;
    @BindView(R.id.fake_status_bar)
    View fake_status_bar;
    @BindView(R.id.bt_more_clear)
    Button btMoreClear;
    @BindView(R.id.upload)
    Button btupload;
    Unbinder unbinder;
    private String name;
    private String pwd;

    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private ImagePickerAdapter adapter;
    private HttpUtil httpUtil;

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.fragment_more, null);
        unbinder = ButterKnife.bind(this, view);

        httpUtil = new HttpUtil();
        name = SharedPreferencesUtil.getString(mContext, "name", "00000");
        pwd = SharedPreferencesUtil.getString(mContext, "pwd", "0000");
        getStateBarHeigh();
        fake_status_bar.setBackgroundColor(ContextCompat.getColor(mContext,R.color.theme_color));
        return view;
    }

    private void getStateBarHeigh() {
        /**
         * 获取状态栏高度——方法1
         * */
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
            fake_status_bar.setMinimumHeight(statusBarHeight1);
        }
        Log.e("WangJ", "状态栏-方法1:" + statusBarHeight1);
    }

    //加载数据
    private void initWidget() {

        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(mContext, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);

        recyclerView_imagepick.setLayoutManager(new GridLayoutManager(mContext, 4));
        recyclerView_imagepick.setHasFixedSize(true);
        recyclerView_imagepick.setAdapter(adapter);
    }


    /**
     * 展示对话框
     * @param listener
     * @param names
     * @return
     */
    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog((Activity) mContext, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isHidden()) {
            dialog.show();
        }
        return dialog;
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                Intent intent1 = new Intent(mContext, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                                // intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);


                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(mContext, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }


    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

    @Override
    public void initData() {
        super.initData();
        initWidget();
        wbshowData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    @Override
    public void onResume() {
        super.onResume();
        scro_webview.onResume();

    }

    /**
     * 第二个webview加载数据
     */
    private void wbshowData() {

        //scro_webview.loadUrl("https://www.baidu.com");


        scro_webview.loadUrl("http://www.4399.com");
        //webView.loadUrl("https://www.sina.com.cn");
        //www.admin.weitengchina.com   admin123



        //声明WebSettings子类
        WebSettings webSettings = scro_webview.getSettings();
        //设置自适应屏幕，两者合用
        scro_webview.setInitialScale(1);//这个很重要
        webSettings.setUseWideViewPort(true);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setAllowContentAccess(true);
        //支持通过JS打开新窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true);

        //优先使用缓存:
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。



        scro_webview.setWebViewClient(new WebViewClient() {

              /*
              @Override
               public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;

                   //这种方法解决重定向问题   按返回键,不起作用,死循环
                   WebView.HitTestResult hitTestResult = view.getHitTestResult();
                   //hitTestResult==null解决重定向问题
                   if (!TextUtils.isEmpty(url) && hitTestResult == null) {
                       view.loadUrl(url);
                       return true;
                   }
                   //WebBackForwardList mWebBackForwardList = webview.copyBackForwardList();//获取栈内存在的URL
                   //for (int i = 0, p = mWebBackForwardList.getSize(); i < p; i++) {
                   //  Log.e("====", "" + mWebBackForwardList.getItemAtIndex(i).getUrl());
                   //}
                   return false;
               }*/

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    view.loadUrl(request.getUrl().toString());
                }

                return true;
            }
        });



    }

    @Override
    public void onPause() {
        super.onPause();
        scro_webview.onPause();

    }

    @OnClick({R.id.bt_more_clear,R.id.upload})
    public void onViewClicked(View v) {
        switch(v.getId()){
            case R.id.bt_more_clear:
                Toast.makeText(mContext, name+"~~~~~~"+pwd, Toast.LENGTH_SHORT).show();
                //清除数据
                SharedPreferencesUtil.DeleteData(mContext);
                break;
            case R.id.upload:
                if(images!=null){
                    upFile(images);
                }
                break;
            default:

                break;
        }
    }

    /**
     * 上传文件
     * @param images
     */
    private void upFile(ArrayList<ImageItem> images) {

        try{
            String url= Constants.BASE_URl_IMAGE;
            httpUtil.postFileRequest(url,null,images,new MyStringCallBack(){
                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                }

                @Override
                public void onResponse(String response, int id) {
                    super.onResponse(response, id);
                    //返回图片的地址
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            Log.i("printStackupFile", "upFile: "+e.getMessage());
        }



    }


}
